package com.frame.web;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.frame.Page;
import com.frame.Result;
import com.frame.domain.Department;
import com.frame.domain.Permission;
import com.frame.domain.Role;
import com.frame.domain.User;
import com.frame.domain.UserRole;
import com.frame.service.DeptService;
import com.frame.service.PermissionService;
import com.frame.service.RoleService;
import com.frame.service.UserRoleService;
import com.frame.service.UserService;
import com.frame.support.Tree;
import com.mini.core.Record;
import com.mini.core.utils.StrKit;

/**
 * @author sxjun1904
 * @since 2016-8-8
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    private static final Logger log = LoggerFactory.
            getLogger(UserController.class);

    /*@Autowired
    private DefaultPasswordService passwordService;
*/
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    private DeptService deptService;
    
    /**
     * 用户页面
     * @param model
     * @param request
     * @param response
     * @param treeId
     * @return
     */
    @RequiresPermissions("user:list")
    @RequestMapping(value = "list")
    public String list(Model model, HttpServletRequest request, HttpServletResponse response,String treeId) {
    	Page<Record> page = userService.paginateResult(new Page<Record>(request, response),treeId);
    	addPage(model,page);
        return "user/userList";
    }
    
    /**
     * 用户表单
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value = "form")
    public String form(Model model, HttpServletRequest request, HttpServletResponse response,String id) {
    	if(StrKit.notBlank(id)){
    		User m = userService.findById(id);
    		model.addAttribute("user", m);
    	}
        return "user/userForm";
    }
    
    
    /**
     * 用户角色表单
     * @param model
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value = "userRoleForm")
    public String userRoleForm(Model model, HttpServletRequest request, HttpServletResponse response,String id) {
    	if(StrKit.notBlank(id)){
    		List records = userRoleService.findByUserId(id);
    		model.addAttribute("records", records);
    		model.addAttribute("userid", id);
    	}
        return "user/userRoleForm";
    }
    
    /**
     * 用户保存
     * @param user
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public Result save(User user) {
    	if(Tree.TREE_ROOT_ID.equals(user.getDeptid()))
    		user.setDeptid(null);
    	if(StrKit.notBlank(user.getId()))
    		userService.update(user);
    	else{
    		user.setCreatetime(new Date());
        	userService.save(user);
    	}
        return success();
    }
    
    /**
     * 保存用户角色
     * @param userid
     * @param roleids
     * @return
     */
    @RequestMapping(value = "userRoleSave")
    @ResponseBody
    public Result userRoleSave(String userid,String roleids){
    	userRoleService.deleteByUserid(userid);
    	if(StrKit.isBlank(roleids))
    		return success();
    	String[] _roles = roleids.split(",");
    	for(String r : _roles){
    		UserRole userRole = new UserRole();
    		userRole.setRoleid(r);
    		userRole.setUserid(userid);
    		userRole.setCreatetime(new Date());
    		userRoleService.save(userRole);
    	}
    	return success();
    }
    
    /**
     * 用户删除
     * @param id
     * @return
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public Result delete(String id) {
    	userService.delete(id);
        return success();
    }
    
    /**
     * 用户部门树
     * @return
     */
    @RequestMapping(value = "tree")
    @ResponseBody
    public List<Tree> tree() {
    	List<Tree> trees = new ArrayList<Tree>();
    	Tree root = new Tree();
    	root.setId(Tree.TREE_ROOT_ID);
    	root.setName("用户树");
    	root.setOpen(true);
    	trees.add(root);
    	List<Department> depts = deptService.findAll();
    	for(Department dept : depts){
    		Tree tree = new Tree();
    		tree.setId(dept.getId());
    		tree.setName(dept.getName());
    		if(StrKit.isBlank(dept.getParentid())){
    			tree.setpId(Tree.TREE_ROOT_ID);
	    		tree.setOpen(true);
    		}else
    			tree.setpId(dept.getParentid());
    		trees.add(tree);
    	}
    	List<User> users = userService.findAll();
    	for(User user : users){
    		Tree tree = new Tree();
    		tree.setId(user.getId());
    		tree.setName(user.getUsername());
    		tree.setpId(user.getDeptid());
    		trees.add(tree);
    	}
    	return trees;
    }
    
    
    
    
    
 /////////////////////////////////////////////////////////////////////////////////   
    @RequestMapping(value = "add", method = GET)
    public List<User> addUser() {
        return null;
    }
    
    @RequestMapping(value = "getAll", method = GET)
    @RequiresAuthentication
    @RequiresUser
    public List<User> getAll() {
        return null;
    }

    @RequestMapping(value = "do_something", method = GET)
    @RequiresAuthentication
    @RequiresRoles("DO_SOMETHING")
    public List<User> dontHavePermission() {
        return null;
    }

    @RequestMapping(method = PUT)
    public void initScenario() {
        log.info("Initializing scenario..");
        // clean-up users, roles and permissions
        userService.deleteAll();
        //roleService.deleteAll();
        //permissionService.deleteAll();
        // define permissions
        final Permission p1 = new Permission();
        p1.setPermname("VIEW_ALL_USERS");
        //permissionService.save(p1);
        final Permission p2 = new Permission();
        p2.setPermname("DO_SOMETHING");
        //permissionService.save(p2);
        // define roles
        final Role roleAdmin = new Role();
        roleAdmin.setRolename("ADMIN");
        //roleAdmin.setPermid(p1.getId());
        roleService.save(roleAdmin);
        // define user
        final User user = new User();
        user.setActive(true);
        user.setCreatetime(new Date());
        user.setEmail("pjpires@gmail.com");
        user.setUsername("Paulo Pires");
        //user.setPassword(passwordService.encryptPassword("123qwe"));
        user.setRoleid(roleAdmin.getId());
        userService.save(user);
        log.info("Scenario initiated.");
    }
    public static void main(String[] args) {
		System.out.println(UUID.randomUUID().toString());
	}
}
